/*
Error reading included file Templates/Classes/../Licenses/license-C:\Users\Rob\Documents\Projects\Java\Libraries and Frameworks\Commons\Apache 2.0.txt *
 * DelegatingPlugInManager.java
 *
 * Created on Jun 25, 2011 at 4:44:44 PM
 */
package org.robcash.commons.plugin.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.robcash.commons.plugin.BasePlugInManager;
import org.robcash.commons.plugin.PlugIn;
import org.robcash.commons.plugin.PlugInException;
import org.robcash.commons.plugin.PlugInManager;
import org.robcash.commons.plugin.PlugInManagerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * DelegatingPlugInManager
 * @author Rob Cash
 * @param <P> Type of plug-in managed by this manager
 */
public class DelegatingPlugInManager<P extends PlugIn> extends BasePlugInManager<P> implements PlugInManager<P>
{
	@SuppressWarnings("unused")
	private static final Logger LOG = LoggerFactory.getLogger(DelegatingPlugInManager.class);

	private final List<PlugInManager<P>> delegates;

	/**
	 * Create delegating plug-in manager
	 */
	public DelegatingPlugInManager()
	{
		this.delegates = new ArrayList<PlugInManager<P>>();
	}

	/**
	 * Set the managers to which this manager will delegate
	 * @param managers
	 */
	public void setDelegateManagers(final List<PlugInManager<P>> managers)
	{
		delegates.clear();
		delegates.addAll(managers);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void discoverPlugIns() throws PlugInManagerException
	{
		for( PlugInManager<P> delegate : delegates )
		{
			delegate.discoverPlugIns();
		}
	}

	/**
	 * {@inheritDoc}
	 * @throws PlugInException
	 */
	@Override
	public boolean unregisterPlugIn(final P plugIn) throws PlugInException
	{
		boolean unregistered = super.unregisterPlugIn(plugIn);
		for( PlugInManager<P> delegate : delegates )
		{
			unregistered = unregistered || delegate.unregisterPlugIn(plugIn);
		}

		return unregistered;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Collection<P> getPlugIns()
	{
		List<P> allPlugIns = new ArrayList<P>(super.getPlugIns());
		for( PlugInManager<P> delegate : delegates )
		{
			allPlugIns.addAll(delegate.getPlugIns());
		}

		return Collections.unmodifiableList(allPlugIns);
	}

}
